﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Lily.Admin
{
    public partial class Dictionary1 : System.Web.UI.Page
    {
        private LilyDataContext DC;
        private void ClearTxt(object sender, EventArgs e)
        {
            ddlType.SelectedIndex = 0;
            txtName.Text = string.Empty;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            DC = new LilyDataContext();
            if (!IsPostBack)
            {
                GridBind();
                ddlType.DataSource = from bar in DC.DictionaryType select bar;
                ddlType.DataTextField = "name";
                ddlType.DataValueField = "typeID";
                ddlType.DataBind();
            }
            Master.AddEventRegister(ClearTxt);
        }

        private void GridBind()
        {
            var foo = from bar in DC.Dictionary select new { bar.ID, bar.name, bar.value };
            Master.GridBind(foo,"id");
            if (IsPostBack)
            {
                Master.UpdateGrid();
            }
        }

        


        protected void btnOK_Click(object sender, EventArgs e)
        {
            //save data
            Lily.Dictionary dictionary = new Lily.Dictionary();
            dictionary.typeID = int.Parse(ddlType.SelectedValue);
            dictionary.name = txtName.Text;

            DictionaryType type = DC.DictionaryType.Single(a => a.typeID == dictionary.typeID);
            var maxValue = (from bar in DC.Dictionary where bar.typeID== type.typeID select bar.value).Max();
            if (type.valueMode == 0)
            {
                //递增
                dictionary.value = maxValue + 1;
            }
            else if (type.valueMode == 1)
            {
                //2的N次方
                dictionary.value = maxValue == 0 ? 2 : maxValue * 2;
            }
            DC.Dictionary.InsertOnSubmit(dictionary);
            DC.SubmitChanges();
            GridBind();
        }
    }
}
